import { Repository , getRepository } from 'typeorm';
import { BaseContext } from "koa";
import { validate, ValidationError } from "class-validator";
import { SeasonType } from '../entity/season_type';

export default class SeasonTypeControl {
    public static async saveSeasonType(seasonType: Array<SeasonType>) {
        const seasonTypeRepository: Repository<SeasonType> = getRepository(SeasonType);
        const errors: ValidationError[] = await validate(seasonType);
        if(errors.length > 0) console.log(errors);
        else await seasonTypeRepository.save(seasonType);
    }
    public static querySeasonTypeAll(): Promise<Array<SeasonType>> {
        return new Promise(async (resolve,reject) => {
            const seasonTypeRepository: Repository<SeasonType> = getRepository(SeasonType);
            let seasonTypes: SeasonType[] = await seasonTypeRepository.find();
            resolve(seasonTypes);
        })
    }

    public static querySeasonTypeByName(name: string): Promise<SeasonType> {
        return new Promise(async (resolve,reject) => {
            const seasonTypeRepository: Repository<SeasonType> = getRepository(SeasonType);
            let seasonType: SeasonType = await seasonTypeRepository.findOne({
                name
            });
            resolve(seasonType);
        })
    }

    public static async getSeasonTypeLists(ctx: BaseContext) {
        try {
            const SeasonTypeRepository: Repository<SeasonType> = getRepository(SeasonType);
            const seasonTypeLists: Array<SeasonType> = await SeasonTypeRepository.find();
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                seasonTypeLists,
            });
        } catch (error) {
            ctx.status = 500;
            ctx.app.emit('error', {
                code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                message: ctx.ERROR.ERRORMSG_SYSTEMERROR
            }, ctx);
        }
    }

    public static async getSeasonTypeByName(ctx: BaseContext) {
        try {
            const SeasonTypeRepository: Repository<SeasonType> = getRepository(SeasonType);
            const seasonType: Array<SeasonType> = await SeasonTypeRepository.find({
                name: ctx.query.name
            })
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                seasonType,
            });
        } catch (error) {
            ctx.status = 500;
            ctx.app.emit('error', {
                code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                message: ctx.ERROR.ERRORMSG_SYSTEMERROR
            }, ctx);
        }
    }
}